﻿layui.define('grid', function (exports) {
    var Grid = layui.grid;
    var TreeGrid = {
        config: Grid.config,
        createNew: function (option) {
            var grid = Grid.createNew(option);
            grid.id = option.id || 'id';
            grid.parentid = option.parentid || 'parentid';
            grid.root = option.root || 0;
            grid.order = option.order || grid.id;
            grid.asc = option.asc || 'asc';

            //grid.onCollapse = option.onCollapse;
            //grid.onExpand = option.onExpand;

            grid.dataSuccess = function (pageData) {
                if (option.dataSuccess) option.dataSuccess(pageData);
                var treeRows = [];
                treeData(pageData.rows, treeRows, grid.root);
                grid.pageData.rows = treeRows;

                function treeData(rows, tree, pid) {
                    var items = [];
                    $.each(rows, function (_, item) {
                        if (item[grid.parentid] == pid)
                            items.push(item);
                    });

                    items.sort(function (a, b) {
                        var x = a[grid.order],
                            y = b[grid.order];
                        return x == y ? 0 : (x > y ? 1 : -1);
                    });

                    if (items.length > 0) {
                        $.each(items, function (_, item) {
                            tree.push(item);
                            treeData(rows, tree, item[grid.id]);
                        });
                    }
                }
            };



            var HELPER = {
                nodeId: function (node) {
                    var template = /treegrid-([A-Za-z0-9_-]+)/;
                    if (template.test(node.attr('class')))
                        return template.exec(node.attr('class'))[1];
                    else
                        return null;
                },
                nodePid: function (node) {
                    var template = /treegrid-parent-([A-Za-z0-9_-]+)/;
                    if (template.test(node.attr('class')))
                        return template.exec(node.attr('class'))[1];
                    else
                        return null;
                }
            }

            grid.success = function () {
                if (option.success)
                    option.success();
                if (!grid.singleSelect) {
                    grid.elem.find('tbody tr').each(function () {
                        $(this).click(function () {
                            var selected = $(this).hasClass('selected');
                            private_childSelect($(this), selected);
                            var pid = HELPER.nodePid($(this));
                            if (pid != null)
                                private_parentSelect(selected, pid);
                        });
                    });
                    function private_childSelect($tr, selected) {
                        $tr.nextAll().each(function (_, tr) {
                            if ($(tr).find('span.treegrid-indent,span.treegrid-expander').length <= $tr.find('span.treegrid-indent,span.treegrid-expander').length) {
                                return false;
                            }
                            selected ? $(tr).addClass('selected') : $(tr).removeClass('selected');
                            if ($(tr).find('td:first :checkbox').length > 0)
                                $(tr).find('td:first :checkbox')[0].checked = selected;
                        });
                    }
                    function private_parentSelect(selected, pid) {
                        var tr = grid.elem.find('tr.treegrid-' + pid);
                        if (tr.length > 0) {
                            if (selected && !tr.hasClass('selected')) {
                                tr.addClass('selected');
                                if (tr.find('td:first :checkbox').length > 0)
                                    tr.find('td:first :checkbox')[0].checked = true;
                            }
                            else if (tr.nextAll('tr.treegrid-parent-' + pid + '.selected').length == 0) {
                                tr.removeClass('selected');
                                if (tr.find('td:first :checkbox').length > 0)
                                    tr.find('td:first :checkbox')[0].checked = false;
                            }
                            pid = HELPER.nodePid(tr);
                            if (pid != null)
                                private_parentSelect(selected, pid);
                        }
                    }
                }

                grid.elem.find('.grid-body tbody tr').each(function (i, tr) {
                    var id = grid.pageData.rows[i][grid.id],
                        pid = grid.pageData.rows[i][grid.parentid];
                    $(tr).addClass('treegrid-' + id);
                    if (pid != grid.root) $(tr).addClass('treegrid-parent-' + pid);
                });

                var EXPANDER = '<span class="treegrid-expander"></span>',
                    INDENT = '<span class="treegrid-indent"></span>';
                grid.elem.find('.grid-body tbody tr').each(function (i, tr) {
                    tr = $(tr);
                    var id = HELPER.nodeId(tr),
                        pid = HELPER.nodePid(tr);
                    if (tr.next('.treegrid-parent-' + id).length > 0) {
                        $(EXPANDER).on('click', function (event) {
                            if (tr.hasClass('treegrid-expanded')) {
                                tr.removeClass('treegrid-expanded').addClass('treegrid-collapse');
                                tr.nextAll().each(function (_, t) {
                                    if ($(t).find('span.treegrid-indent,span.treegrid-expander').length <= tr.find('span.treegrid-indent,span.treegrid-expander').length) {
                                        return false;
                                    }
                                    $(t).hide();
                                });
                            } else {
                                openChild(tr);
                                function openChild(node) {
                                    node.removeClass('treegrid-collapse').addClass('treegrid-expanded');
                                    node.nextAll('.treegrid-parent-' + HELPER.nodeId(node)).each(function (_, t) {
                                        $(t).show();
                                        if ($(t).hasClass('treegrid-expanded')) {
                                            openChild($(t));
                                        }
                                    });
                                }
                            }
                            grid.resize();
                            event.stopPropagation(); //阻止冒泡 rowClick
                        }).prependTo(tr.addClass('treegrid-expanded').find('td:eq(0)'));
                    } else {
                        tr.find('td:eq(0)').prepend(INDENT);
                    }
                    if (grid.elem.find('tr.treegrid-' + pid).length > 0) {
                        var prevIndentLen = grid.elem.find('tr.treegrid-' + pid).find('.treegrid-expander').prevAll().length;
                        var pindent = '';
                        for (var i = 0; i < prevIndentLen; i++) {
                            pindent += INDENT;
                        }
                        tr.find('td:eq(0)').prepend(pindent + INDENT);
                    }
                });

                /*
                if (option.onCollapse) {
                    
                }
                if (option.onExpand) {
                    
                }*/
            };

            /*
            grid.insertChild = function (data, pid) {

                var node = grid.elem.find('treegrid-' + pid);
                if (node.length == 0) {

                }
            }*/


            return grid;
        }
    };
    exports('treegrid', TreeGrid);
    layui.link(layui.cache.base + 'css/grid.css', null, 'gridcss');
});

